package com.app.controller.exportExcel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.app.common.IdCardNumberMethod;
import com.app.common.SystemConstant;
import com.app.model.*;
import com.app.service.*;
import com.app.service.impl.MilitaryNewSportsServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 军事训练导出
 */
@RestController
@Controller
@RequestMapping("/api/excel")
public class MilitaryAffairsController {
    @Autowired
    private MilitarySportsService militarySportsService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PersonTrainService personTrainService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private PersonService personService;
    @Autowired
    private MilitaryNewSportsServiceImpl militaryNewSportsServiceImpl;

    /**
     * 军事体育导出
     *
     * @param json
     * @param response
     */
    @PostMapping("/militarySportsExcel")
    public void militarySportsExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<MilitarySportsModel> militarySportsModels = militarySportsService.getPlantByIds(appIdList);
        for (int i = 0; i < militarySportsModels.size(); i++) {
            if (militarySportsModels.get(i).getGender() != null && militarySportsModels.get(i).getGender() == 1) {
                militarySportsModels.get(i).setGenderText("男");
            }
            if (militarySportsModels.get(i).getGender() != null && militarySportsModels.get(i).getGender() == 2) {
                militarySportsModels.get(i).setGenderText("女");
            }
            if (militarySportsModels.get(i).getDepartmentId() != null) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(militarySportsModels.get(i).getDepartmentId());
                if (depByDepId != null) {
                    militarySportsModels.get(i).setDepartmentName(depByDepId.getName());
                }
            }
        }
        map.put("list", militarySportsModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.MilitarySportsExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "军事体育花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 军事体育导出（带木马、双杠的）
     *
     * @param json
     * @param response
     */
    @PostMapping("/militarySportsNewExcel")
    public void militarySportsNewExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<MilitarySportsNewModel> militarySportsModels = militaryNewSportsServiceImpl.getPlantByIds(appIdList);
        for (int i = 0; i < militarySportsModels.size(); i++) {
            if (militarySportsModels.get(i).getGender() != null && militarySportsModels.get(i).getGender() == 1) {
                militarySportsModels.get(i).setGenderText("男");
            }
            if (militarySportsModels.get(i).getGender() != null && militarySportsModels.get(i).getGender() == 2) {
                militarySportsModels.get(i).setGenderText("女");
            }
            if (militarySportsModels.get(i).getDepartmentId() != null) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(militarySportsModels.get(i).getDepartmentId());
                if (depByDepId != null) {
                    militarySportsModels.get(i).setDepartmentName(depByDepId.getName());
                }
            }
        }
        map.put("list", militarySportsModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.MilitarySportsExportNewURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "军事体育花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 军事训练
     *
     * @param response
     */
    @PostMapping("/trainExcel")
    public void trainExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        Integer personId = (Integer) json.get("personId");
        Map<String, Object> map = new HashMap<>();
        //获取列表
        List<PersonTrainModel> trainModelList = personTrainService.getTrainList(personId, null);
        PersonModel model = personService.selectById(personId);
        if (!trainModelList.isEmpty()) {
            List<PersonTrainModel> list = new ArrayList<>();
            for (int i = 0; i < trainModelList.size(); i++) {
                CategoryModel model1 = categoryService.getCategoryById(trainModelList.get(i).getTrainDesc());
                if (model1 != null) {
                    trainModelList.get(i).setTrainDesc(model1.getId());
                    trainModelList.get(i).setTrainTotal(model1.getName());//训练总成绩
                }
                String trainResult = trainModelList.get(i).getTrainResult();
                list = JSON.parseObject(trainResult, new TypeReference<List<PersonTrainModel>>() {
                });
                trainModelList.get(i).setId(i + 1);
                trainModelList.get(i).setPositionDesc(model.getPositionDesc());
                trainModelList.get(i).setName(model.getName());
                trainModelList.get(i).setGenderText(model.getGender());
                trainModelList.get(i).setAge(IdCardNumberMethod.getAgeForIdCard(model.getIdcard()));
            }
            for (int i = 0; i < trainModelList.size(); i++) {
                for (int i1 = 0; i1 < list.size(); i1++) {
                    if (list.get(i1).getTrainObject() == 54) {//军事体育
                        trainModelList.get(i).setPhysicalScore(list.get(i1).getTrainScore());
                        trainModelList.get(i).setPhysicalLevel(list.get(i1).getTrainLevelText());
                    }
                    if (list.get(i1).getTrainObject() == 55) {//军事教育
                        trainModelList.get(i).setEducationLevel(list.get(i1).getTrainLevelText());
                    }
                    if (list.get(i1).getTrainObject() == 83) {//理论考核
                        trainModelList.get(i).setTheoreticalScore(list.get(i1).getTrainScore());
                        trainModelList.get(i).setTheoreticalLevel(list.get(i1).getTrainLevelText());
                    }
                    if (list.get(i1).getTrainObject() == 107) {//轻武器操作
                        trainModelList.get(i).setWeaponScore(list.get(i1).getTrainScore());
                        trainModelList.get(i).setWeaponLevel(list.get(i1).getTrainLevelText());
                    }
                    if (list.get(i1).getTrainObject() == 108) {//专业岗位考核
                        trainModelList.get(i).setPostScore(list.get(i1).getTrainScore());
                        trainModelList.get(i).setPostLevel(list.get(i1).getTrainLevelText());
                    }
                }
            }
        }
        map.put("list", trainModelList);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.TrainExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "军事训练评定" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
